package com.bdqn.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * EncodingFilter 字符编码过滤器
 *
 * @author LILIBO
 * @since 2024/5/24
 */
@WebFilter(urlPatterns = "/*", initParams = {@WebInitParam(name = "charset", value = "UTF-8")})
public class EncodingFilter implements Filter {

    /**
     * 字符编码（默认：UTF-8）
     */
    private static String charset = "UTF-8";

    /**
     * 初始化
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        charset = filterConfig.getInitParameter("charset");
    }

    /**
     * 执行过滤操作
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 设置请求和响应的编码
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);

        // 过滤器放行
        filterChain.doFilter(request, response);
    }

    /**
     * 销毁
     */
    public void destroy() {
    }

}
